<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    class="app-container"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      pagination
      background
      border
      height="720"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import {
  getParkList,
  list,
  deleteFacilities,
} from "@/api/basicdata/construction";
import operate from "@/views/configuration/basicdata/construction/components/operate";
import position from "@/views/configuration/basicdata/construction/components/position";
import { dealElectricity } from "@/utils/index";
import auth from "@/plugins/auth";

export default {
  name: "construction",
  dicts: ["building_type", "house_structure"],
  components: {
    operate,
    position,
  },
  data() {
    return {
      parkOptions: [],
      //弹窗
      id: "",
      modelName: "",
      show: false,
      // 部门树选项
      deptList: [],
      deptId: "",
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            address: {
              label: "建筑设施地址:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入建筑设施地址",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              display: true,
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              display: true,
              click: () => this.showModel("operate"),
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            prop: "name",
            label: "建筑设施名称",
            showOverflowTooltip: true,
            minWidth: 120,
          },
          {
            prop: "buildingType",
            label: "建筑类型",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.building_type}
                    value={scope.row.buildingType}
                  />
                </div>
              );
            },
          },
          {
            prop: "address",
            label: "建筑设施地址",
            showOverflowTooltip: true,
            minWidth: 120,
          },
          {
            prop: "parkName",
            label: "园区",
            minWidth: 120,
            showOverflowTooltip: true,
          },
          {
            prop: "buildingName",
            label: "楼幢",
            showOverflowTooltip: true,
          },
          {
            prop: "floor",
            label: "楼层",
            showOverflowTooltip: true,
          },
          {
            prop: "landArea",
            label: "用地面积（m²）",
            width: 140,
            render: (h, params) => {
              let num = dealElectricity(params.row.landArea);
              return h("div", {}, num);
            },
          },
          {
            prop: "buildArea",
            label: "建筑面积（m²）",
            width: 140,
            render: (h, params) => {
              let num = dealElectricity(params.row.buildArea);
              return h("div", {}, num);
            },
          },
          {
            prop: "houseStructure",
            label: "房屋结构",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.house_structure}
                    value={scope.row.houseStructure}
                  />
                </div>
              );
            },
          },
          {
            prop: "direction",
            label: "朝向",
            showOverflowTooltip: true,
          },
          {
            prop: "completionTime",
            label: "竣工日期",
            width: 150,
          },
          {
            prop: "longitude",
            label: "经度",
            width: 120,
          },
          {
            prop: "latitude",
            label: "纬度",
            width: 120,
          },
          {
            label: "操作",
            width: "240",
            fixed: "right",
            render: (h, scope) => {
              return (
                <div>
                  {
                    <el-button
                      v-hasPermi={["architecture:facilities:edit"]}
                      type="text"
                      icon="el-icon-view"
                      size="small"
                      onClick={() => {
                        this.showModel("position", scope.row);
                      }}
                    >
                      布局详情
                    </el-button>
                  }
                  {
                    <el-button
                      v-hasPermi={["architecture:facilities:edit"]}
                      type="text"
                      size="small"
                      icon="el-icon-edit"
                      onClick={() => {
                        this.showModel("operate", scope.row);
                      }}
                    >
                      编辑
                    </el-button>
                  }
                  {
                    <el-button
                      v-hasPermi={["architecture:facilities:remove"]}
                      type="text"
                      size="small"
                      icon="el-icon-delete"
                      onClick={() => {
                        this.handleOperDelete(scope.row);
                      }}
                      style="color:red"
                    >
                      删除
                    </el-button>
                  }
                </div>
              );
            },
          },
        ],
        data: [],
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
    };
  },
  mounted() {
    // 添加总会管理员角色判断zjuadmin
    this.judgePermi();
    this.getPark();
    this.initData();
  },
  methods: {
    getPark() {
      getParkList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.parkOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300406");
        });
    },
    judgePermi() {
      if (auth.hasPermi("architecture:facilities:add")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
    //删除
    handleOperDelete(row) {
      let that = this;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.$store.commit("app/updateApiCount", "add");
          deleteFacilities(row.id)
            .then((res) => {
              that.$store.commit("app/updateApiCount");
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }

              that.$message.success("已删除!");
              that.initData();
            })
            .catch((err) => {
              that.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300405");
            });
        })
        .catch(() => {});
    },
    dictPark(val) {
      const data = this.parkOptions.find((item) => item.id === val);
      let result = data.name;
      return result;
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows.map((item) => {
            item.parkName = that.dictPark(item.parkId);
            return item;
          });
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300401");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        sysDeptId: this.deptId,
        ...this.$refs?.form?.getFieldsValue(),
      };
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
  },
};
</script>
